package com.ningju.procurement.common.service;

import com.ningju.procurement.common.bean.BaseBean;
import com.ningju.procurement.common.dao.BaseDao;
import org.apache.commons.collections.CollectionUtils;
import org.joda.time.DateTime;

import java.util.List;

/**
 * Service实现基类
 * @author imhu
 *
 * @param <T> Dao
 * @param <E> Bean
 */
public class BaseServiceImpl<T extends BaseDao<E>, E extends BaseBean> implements BaseService<T, E> {

	@Override
	public boolean save(T t, E e) {
		if(null == e) return false;
		
		int result = -1;
		if(!this.isSaved(e)) {
			e.setCreatedAt(DateTime.now());
			e.setUpdatedAt(DateTime.now());
			result = t.insert(e);
			if(result < 1) {
				throw new RuntimeException("新增数据失败!");
			}
		} else {
			e.setUpdatedAt(DateTime.now());
			result = t.updateByIdSelective(e); //只更新不是null的字段
		}
		return result > -1;
	}
	
	@Override
	public boolean deleteByIds(T t, List<Long> ids) {
		return true;
	}

	@Override
	public List<E> selectByIds(T t, List<Long> ids) {
		if(CollectionUtils.isEmpty(ids)) return null;
		return t.selectByIds(ids);
	}
	
	@Override
	public boolean insertBatch(T t, List<E> datas) {
		if(CollectionUtils.isEmpty(datas)) {
			return false;
		}
		datas.parallelStream().forEach((e) -> {
			e.setCreatedAt(DateTime.now());
			e.setUpdatedAt(DateTime.now());
		});
		return t.insertMulti(datas) >= datas.size();
	}
	
	/**
	 * 判断是否已经保存
	 * @param e
	 * @return
	 */
	protected boolean isSaved(E e) {
		if(null == e.getId() || e.getId() < 1) {
			return false;
		}
		return true;
	}
	
}